package com.knowswift.issues.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.knowswift.common.bean.issue.po.Authorize;
import com.knowswift.common.bean.issue.po.SysUser;
import com.knowswift.common.bean.issue.vo.ModuleDto;
import com.knowswift.common.bean.project.po.Project;
import com.knowswift.issues.mapper.SysUserMapper;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.apache.shiro.crypto.hash.Sha256Hash;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author CTL
 * @create 2025-07-24 16:34
 */
@Service
public class SysUserService  extends ServiceImpl<SysUserMapper, SysUser> {
    @Resource
    private AuthorizeService authorizeService;
    public void ProjectAuthorize(Long userId, List<ModuleDto> moduleList) {
        //删除原有客户授权项目
        authorizeService.getBaseMapper().deleteTermiteAuthorizeByUserId(userId);
        //保存新的客户授权项目
        List<Authorize> authorizeEntityList = new ArrayList<>();
        for (ModuleDto module : moduleList) {
            for (Project project : module.getProjects()) {
                Authorize authorize = new Authorize();
                authorize.setUserId(userId);
                authorize.setModuleId(module.getModuleId());
                authorize.setModuleName(module.getModuleName());
                authorize.setModuleOrder(module.getModuleOrder());
                authorize.setProjectName(project.getProjectName());
                authorize.setProjectOrder(project.getProjectOrder());
                authorizeEntityList.add(authorize);
            }
        }
        authorizeService.saveBatch(authorizeEntityList);
    }

    public void saveUser(SysUser user) {
        user.setCreateTime(new Date());
        //sha256加密
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setPassword(new Sha256Hash(user.getPassword(), salt).toHex());
        user.setSalt(salt);
        this.save(user);
    }

    public void updateUser(SysUser user) {
        if(StringUtils.isBlank(user.getPassword())){
            user.setPassword(null);
        }else{
            user.setPassword(new Sha256Hash(user.getPassword(), user.getSalt()).toHex());
        }
        this.updateById(user);

    }

    public SysUser queryByUserName(String username) {
        return baseMapper.queryByUserName(username);
    }
    public SysUser queryByUserNameNotId(String username,Long userId) {
        return baseMapper.queryByUserNameNotId(username,userId);
    }
}
